import logging
import queue
import re
import threading
from datetime import timedelta

from aiogram import types
from aiogram.dispatcher import FSMContext
from aiogram.dispatcher.filters import Text
from aiogram.dispatcher.filters.state import State, StatesGroup
from aiogram.types import ParseMode

import client
import client_kb
import sqlite_db
from common_utils import paste_watermark
from create_bot import dp
from handlers.users.generate.de_country.de_country_menu import create_germany
from .utils import is_deutsch

logger = logging.getLogger(__name__)


class DE_BILL_FSM(StatesGroup):
    doc_type_select = State()
    bill_client_first_name = State()
    bill_client_last_name = State()
    bill_client_sex = State()
    bill_client_street = State()
    bill_client_house = State()
    bill_client_index = State()
    bill_client_city = State()
    bill_edit_data = State()


data_fields = [
    {"title": "Имя", "key": "client_first_name"},
    {"title": "Фамилия", "key": "client_last_name"},
    {"title": "Пол", "key": "client_sex"},
    {"title": "Улица", "key": "client_street"},
    {"title": "Номер дома", "key": "client_house"},
    {"title": "Индкс", "key": "client_index"},
    {"title": "Город", "key": "client_city"},
]

back_kb = types.ReplyKeyboardMarkup(resize_keyboard=True)
back_button = types.KeyboardButton(text="Назад ◀️")
back_kb.add(back_button)


async def data_checkup(user_id: int, state: FSMContext):
    try:
        data = await state.get_data()
        checkup_text = "Данные клиента:\n"
        for field in data_fields:
            if field["key"] in data:
                checkup_text += f"✅{field['title']}: {data[field['key']]}\n"
            else:
                checkup_text += f"{field['title']}:\n"
        if "message_to_edit_id" in data:
            await dp.bot.delete_message(
                chat_id=user_id, message_id=data["message_to_edit_id"]
            )
        return (await dp.bot.send_message(chat_id=user_id, text=checkup_text))[
            "message_id"
        ]
    except:
        pass


async def delete_user_reply(user_id: int, message_id: int):
    try:
        await dp.bot.delete_message(chat_id=user_id, message_id=message_id)
    except Exception as e:
        logger.warning(f"Unable to delete user message: {e}")


# @dp.message_handler(Text(equals='Bill 🇩🇪'), state="*")
# async def doc_type(message: types.Message, state: FSMContext):
#     print(message.text)
#     if message.text == "Bill 🇩🇪":
#         type = "bill"
#         await sqlite_db.sql_add_country_user(message.from_user.id, "de_bill")
#         await state.update_data(type=type)
#         await dp.bot.send_photo(
#             chat_id=message.from_user.id, photo=InputFile("./files/de_bill/example.png")
#         )
#         await bill_client_first_name_input(message, state)
#     if message.text == "ID 🇩🇪":
#         type = "id"
#         await sqlite_db.sql_add_country_user(message.from_user.id, "de_id")
#         await state.update_data(type=type)
#         await dp.bot.send_photo(
#             chat_id=message.from_user.id, photo=InputFile("./files/de_id/example.jpg")
#         )
#         await id_client_first_name_input(message, state)


@dp.message_handler(Text(equals="Bill 🇩🇪"), state=DE_BILL_FSM.doc_type_select)
async def bill_client_first_name_input(message: types.Message, state: FSMContext):
    await sqlite_db.sql_add_country_user(message.from_user.id, "de_bill")
    await state.update_data(type="bill")
    message_to_edit_id = await data_checkup(message.from_user.id, state)
    await state.update_data(message_to_edit_id=message_to_edit_id)
    question_message_id = (
        await message.answer(
            "Введите имя✏️\n",
            parse_mode=ParseMode.HTML,
            reply_markup=back_kb,
        )
    )["message_id"]
    await state.update_data(question_message_id=question_message_id)
    await DE_BILL_FSM.bill_client_first_name.set()


@dp.message_handler(
    lambda message: "Назад ◀️" not in message.text,
    state=DE_BILL_FSM.bill_client_first_name,
)
async def bill_client_first_name_validate(message: types.Message, state: FSMContext):
    client_first_name = None
    await delete_user_reply(message.from_user.id, message.message_id)
    data = await state.get_data()

    if "question_message_id" in data:
        await dp.bot.delete_message(
            chat_id=message.from_user.id, message_id=data["question_message_id"]
        )
    else:
        logger.warning("question_message_id not found in state data")

    if re.match("^[A-Za-z `]+$", message.text) is not None or is_deutsch(message.text):
        client_first_name = message.text
    if client_first_name is None:
        message_to_edit_id = await data_checkup(message.from_user.id, state)
        await state.update_data(message_to_edit_id=message_to_edit_id)
        question_message_id = (
            await message.answer(
                text="❌Введите имя в правильном формате.\n"
                "<i>Формат ввода: только латинские буквы.</i>",
                parse_mode=ParseMode.HTML,
                reply_markup=back_kb,
            )
        )["message_id"]
        await state.update_data(question_message_id=question_message_id)
    else:
        await state.update_data(
            client_first_name=client_first_name.replace("ß", "ẞ").upper()
        )
        if "edit_mode" in data:
            return await start_generate(message, state)
        message_to_edit_id = await data_checkup(message.from_user.id, state)
        await state.update_data(message_to_edit_id=message_to_edit_id)
        await bill_client_last_name_input(message, state)


async def bill_client_last_name_input(message: types.Message, state: FSMContext):
    message_to_edit_id = await data_checkup(message.from_user.id, state)
    await state.update_data(message_to_edit_id=message_to_edit_id)
    question_message_id = (
        await message.answer(
            "Введите фамилию✏️", parse_mode=ParseMode.HTML, reply_markup=back_kb
        )
    )["message_id"]
    await state.update_data(question_message_id=question_message_id)
    await DE_BILL_FSM.bill_client_last_name.set()


@dp.message_handler(
    lambda message: "Назад ◀️" not in message.text,
    state=DE_BILL_FSM.bill_client_last_name,
)
async def bill_client_last_name_validate(message: types.Message, state: FSMContext):
    client_last_name = None
    await delete_user_reply(message.from_user.id, message.message_id)
    data = await state.get_data()

    if "question_message_id" in data:
        await dp.bot.delete_message(
            chat_id=message.from_user.id, message_id=data["question_message_id"]
        )
    else:
        logger.warning("question_message_id not found in state data")

    if re.match("^[A-Za-z `]+$", message.text) is not None or is_deutsch(message.text):
        client_last_name = message.text
    if client_last_name is None:
        message_to_edit_id = await data_checkup(message.from_user.id, state)
        await state.update_data(message_to_edit_id=message_to_edit_id)
        question_message_id = (
            await message.answer(
                text="❌Введите фамилию в правильном формате.\n"
                "<i>Формат ввода: только латинские буквы.</i>",
                parse_mode=ParseMode.HTML,
                reply_markup=back_kb,
            )
        )["message_id"]
        await state.update_data(question_message_id=question_message_id)
    else:
        await state.update_data(
            client_last_name=client_last_name.replace("ß", "ẞ").upper()
        )
        if "edit_mode" in data:
            return await start_generate(message, state)
        message_to_edit_id = await data_checkup(message.from_user.id, state)
        await state.update_data(message_to_edit_id=message_to_edit_id)
        await id_client_sex_input(message, state)


async def id_client_sex_input(message: types.Message, state: FSMContext):
    message_to_edit_id = await data_checkup(message.from_user.id, state)
    await state.update_data(message_to_edit_id=message_to_edit_id)
    kb = types.ReplyKeyboardMarkup(resize_keyboard=True)
    kb.add(types.KeyboardButton(text="Мужской 🙎🏻‍♂️"))
    kb.add(types.KeyboardButton(text="Женский 🙍🏻‍♀️"))
    kb.add(back_button)
    question_message_id = (
        await message.answer(
            "Выберите пол\n", parse_mode=ParseMode.HTML, reply_markup=kb
        )
    )["message_id"]
    await state.update_data(question_message_id=question_message_id)
    await DE_BILL_FSM.bill_client_sex.set()


@dp.message_handler(
    lambda message: "Назад ◀️" not in message.text, state=DE_BILL_FSM.bill_client_sex
)
async def id_client_sex_validate(message: types.Message, state: FSMContext):
    await delete_user_reply(message.from_user.id, message.message_id)
    data = await state.get_data()

    if "question_message_id" in data:
        await dp.bot.delete_message(
            chat_id=message.from_user.id, message_id=data["question_message_id"]
        )
    else:
        logger.warning("question_message_id not found in state data")

    if message.text == "Мужской 🙎🏻‍♂️":
        sex = "M"
    elif message.text == "Женский 🙍🏻‍♀️":
        sex = "F"
    else:
        message_to_edit_id = await data_checkup(message.from_user.id, state)
        await state.update_data(message_to_edit_id=message_to_edit_id)
        kb = types.ReplyKeyboardMarkup(resize_keyboard=True)
        kb.add(types.KeyboardButton(text="Мужской 🙎🏻‍♂️"))
        kb.add(types.KeyboardButton(text="Женский 🙍🏻‍♀️"))
        kb.add(back_button)
        question_message_id = (
            await message.answer(
                text="❌Выберите пол через клавиатуру.\n",
                parse_mode=ParseMode.HTML,
                reply_markup=kb,
            )
        )["message_id"]
        return await state.update_data(question_message_id=question_message_id)
    logger.info(f"Пользователь {message.from_user.id} ввёл пол")
    await state.update_data(client_sex=sex)
    if "edit_mode" in data:
        return await start_generate(message, state)
    message_to_edit_id = await data_checkup(message.from_user.id, state)
    await state.update_data(message_to_edit_id=message_to_edit_id)
    await bill_client_street_input(message, state)


async def bill_client_street_input(message: types.Message, state: FSMContext):
    message_to_edit_id = await data_checkup(message.from_user.id, state)
    await state.update_data(message_to_edit_id=message_to_edit_id)
    question_message_id = (
        await message.answer(
            "Введите улицу✏️", parse_mode=ParseMode.HTML, reply_markup=back_kb
        )
    )["message_id"]
    await state.update_data(question_message_id=question_message_id)
    await DE_BILL_FSM.bill_client_street.set()


@dp.message_handler(
    lambda message: "Назад ◀️" not in message.text, state=DE_BILL_FSM.bill_client_street
)
async def bill_client_street_validate(message: types.Message, state: FSMContext):
    client_street = None
    await delete_user_reply(message.from_user.id, message.message_id)
    data = await state.get_data()

    if "question_message_id" in data:
        await dp.bot.delete_message(
            chat_id=message.from_user.id, message_id=data["question_message_id"]
        )
    else:
        logger.warning("question_message_id not found in state data")

    if re.match("^[A-Za-z `]+$", message.text) is not None or is_deutsch(message.text):
        client_street = message.text
    if client_street is None:
        message_to_edit_id = await data_checkup(message.from_user.id, state)
        await state.update_data(message_to_edit_id=message_to_edit_id)
        question_message_id = (
            await message.answer(
                text="❌Введите улицу в правильном формате.\n"
                "<i>Формат ввода: только латинские буквы.</i>",
                parse_mode=ParseMode.HTML,
                reply_markup=back_kb,
            )
        )["message_id"]
        await state.update_data(question_message_id=question_message_id)
    else:
        await state.update_data(client_street=client_street.replace("ß", "ẞ").upper())
        if "edit_mode" in data:
            return await start_generate(message, state)
        message_to_edit_id = await data_checkup(message.from_user.id, state)
        await state.update_data(message_to_edit_id=message_to_edit_id)
        await bill_client_house_input(message, state)


async def bill_client_house_input(message: types.Message, state: FSMContext):
    message_to_edit_id = await data_checkup(message.from_user.id, state)
    await state.update_data(message_to_edit_id=message_to_edit_id)
    kb = types.ReplyKeyboardMarkup(resize_keyboard=True)
    kb.add(types.KeyboardButton(text="Пропустить"))
    kb.add(back_button)
    question_message_id = (
        await message.answer(
            "Введите номер дома✏️\n" "либо нажмите пропустить",
            parse_mode=ParseMode.HTML,
            reply_markup=kb,
        )
    )["message_id"]
    await state.update_data(question_message_id=question_message_id)
    await DE_BILL_FSM.bill_client_house.set()


@dp.message_handler(
    lambda message: "Назад ◀️" not in message.text, state=DE_BILL_FSM.bill_client_house
)
async def bill_client_house_validate(message: types.Message, state: FSMContext):
    client_house = None
    await delete_user_reply(message.from_user.id, message.message_id)
    data = await state.get_data()

    if "question_message_id" in data:
        await dp.bot.delete_message(
            chat_id=message.from_user.id, message_id=data["question_message_id"]
        )
    else:
        logger.warning("question_message_id not found in state data")

    if message.text == "Пропустить":
        client_house = " "
    else:
        if re.match("^\d+$", message.text) is not None:
            client_house = message.text
    if client_house is None:
        message_to_edit_id = await data_checkup(message.from_user.id, state)
        await state.update_data(message_to_edit_id=message_to_edit_id)
        kb = types.ReplyKeyboardMarkup(resize_keyboard=True)
        kb.add(types.KeyboardButton(text="Пропустить"))
        kb.add(back_button)
        question_message_id = (
            await message.answer(
                text="❌Введите номер дома в правильном формате.\n"
                "<i>Формат ввода: число от 1 до 100.</i>",
                parse_mode=ParseMode.HTML,
                reply_markup=kb,
            )
        )["message_id"]
        await state.update_data(question_message_id=question_message_id)
    else:
        await state.update_data(client_house=client_house)
        if "edit_mode" in data:
            return await start_generate(message, state)
        message_to_edit_id = await data_checkup(message.from_user.id, state)
        await state.update_data(message_to_edit_id=message_to_edit_id)
        await bill_client_index_input(message, state)


async def bill_client_index_input(message: types.Message, state: FSMContext):
    message_to_edit_id = await data_checkup(message.from_user.id, state)
    await state.update_data(message_to_edit_id=message_to_edit_id)
    question_message_id = (
        await message.answer(
            "Введите индекс✏️\n" "Формат ввода: XXXXX.\n" "<i>X-цифра</i>",
            parse_mode=ParseMode.HTML,
            reply_markup=back_kb,
        )
    )["message_id"]
    await state.update_data(question_message_id=question_message_id)
    await DE_BILL_FSM.bill_client_index.set()


@dp.message_handler(
    lambda message: "Назад ◀️" not in message.text, state=DE_BILL_FSM.bill_client_index
)
async def bill_index_validate(message: types.Message, state: FSMContext):
    client_index = None
    await delete_user_reply(message.from_user.id, message.message_id)
    data = await state.get_data()

    if "question_message_id" in data:
        await dp.bot.delete_message(
            chat_id=message.from_user.id, message_id=data["question_message_id"]
        )
    else:
        logger.warning("question_message_id not found in state data")

    if re.match(r"\b\d{5}\b", message.text) is not None:
        client_index = message.text
    if client_index is None:
        message_to_edit_id = await data_checkup(message.from_user.id, state)
        await state.update_data(message_to_edit_id=message_to_edit_id)
        question_message_id = (
            await message.answer(
                text="❌Введите индекс в правильном формате.\n"
                "<i>Формат ввода: только числа.</i>",
                parse_mode=ParseMode.HTML,
                reply_markup=back_kb,
            )
        )["message_id"]
        await state.update_data(question_message_id=question_message_id)
    else:
        await state.update_data(client_index=client_index)
        if "edit_mode" in data:
            return await start_generate(message, state)
        message_to_edit_id = await data_checkup(message.from_user.id, state)
        await state.update_data(message_to_edit_id=message_to_edit_id)
        await bill_client_city_input(message, state)


async def bill_client_city_input(message: types.Message, state: FSMContext):
    message_to_edit_id = await data_checkup(message.from_user.id, state)
    await state.update_data(message_to_edit_id=message_to_edit_id)
    question_message_id = (
        await message.answer(
            "Введите город✏️\n"
            "<i>Формат ввода: название и сокращенное обозначение.\n"
            "Например: TORINO </i>",
            parse_mode=ParseMode.HTML,
            reply_markup=back_kb,
        )
    )["message_id"]
    await state.update_data(question_message_id=question_message_id)
    await DE_BILL_FSM.bill_client_city.set()


@dp.message_handler(
    lambda message: "Назад ◀️" not in message.text, state=DE_BILL_FSM.bill_client_city
)
async def bill_city_validate(message: types.Message, state: FSMContext):
    client_city = None
    await delete_user_reply(message.from_user.id, message.message_id)
    data = await state.get_data()

    if "question_message_id" in data:
        await dp.bot.delete_message(
            chat_id=message.from_user.id, message_id=data["question_message_id"]
        )
    else:
        logger.warning("question_message_id not found in state data")

    if re.match("^[A-Za-z `]+$", message.text) is not None or is_deutsch(message.text):
        client_city = message.text
    if client_city is None:
        message_to_edit_id = await data_checkup(message.from_user.id, state)
        await state.update_data(message_to_edit_id=message_to_edit_id)
        question_message_id = (
            await message.answer(
                text="❌Введите город в правильном формате.\n"
                "<i>Формат ввода: только латинские буквы.</i>",
                parse_mode=ParseMode.HTML,
                reply_markup=back_kb,
            )
        )["message_id"]
        await state.update_data(question_message_id=question_message_id)
    else:
        await state.update_data(client_city=client_city.replace("ß", "ẞ").upper())
        if "edit_mode" in data:
            return await start_generate(message, state)
        message_to_edit_id = await data_checkup(message.from_user.id, state)
        await state.update_data(message_to_edit_id=message_to_edit_id)
        await start_generate(message, state)


state_input_functions = {
    "DE_BILL_FSM:bill_client_first_name": create_germany,
    "DE_BILL_FSM:bill_client_last_name": bill_client_first_name_input,
    "DE_BILL_FSM:bill_client_sex": bill_client_last_name_input,
    "DE_BILL_FSM:bill_client_street": id_client_sex_input,
    "DE_BILL_FSM:bill_client_house": bill_client_street_input,
    "DE_BILL_FSM:bill_client_index": bill_client_house_input,
    "DE_BILL_FSM:bill_client_city": bill_client_index_input,
}


@dp.message_handler(lambda message: message.text == "Назад ◀️", state=DE_BILL_FSM)
async def go_back(message: types.Message, state: FSMContext):
    current_state = str(await state.get_state())
    if current_state in state_input_functions:
        input_function = state_input_functions[current_state]
        await input_function(
            message, state
        )  # вызов функции ввода для предыдущего состояния
    else:
        await message.answer("Unknown state.")


async def start_generate(message: types.Message, state: FSMContext):
    message_to_delete = await message.answer("Ожидайте генерируется...")
    data = await state.get_data()
    try:
        await dp.bot.delete_message(
            chat_id=message.from_user.id, message=data["message_to_edit_id"]
        )
    except:
        pass
    result_queue = queue.Queue()
    bill_thread = threading.Thread(
        target=generate_bill, args=(data, message.from_user.id, result_queue)
    )
    logger.warning(result_queue)
    bill_thread.start()
    bill_thread.join()
    result = result_queue.get()
    logger.warning(result)
    if "Error" in result:
        await message.answer("❌Ошибка при генерации изображения")
        logger.warning(f"{result} Ошибка при генерации изображения")
    else:
        await dp.bot.delete_message(
            chat_id=message.from_user.id, message_id=message_to_delete["message_id"]
        )
        with open(result + "_wm.png", "rb") as photo:
            await dp.bot.send_document(chat_id=message.from_user.id, document=photo)
            await message.answer(
                "Завершите покупку документа.", reply_markup=client_kb.kb_de_finish_bill
            )


@dp.callback_query_handler(text="de_change_bill", state="*")
async def de_change_bill(call: types.CallbackQuery, state: FSMContext):
    kb = types.ReplyKeyboardMarkup(one_time_keyboard=True)
    await call.message.delete()
    for field in data_fields:
        kb.add(types.KeyboardButton(text=f'{field["title"]}'))
    edit_message_to_delete_id = (
        await call.message.answer(
            text="Выберите параметр, который хотите изменить", reply_markup=kb
        )
    )["message_id"]
    await state.update_data(edit_message_to_delete_id=edit_message_to_delete_id)
    await DE_BILL_FSM.bill_edit_data.set()


@dp.message_handler(state=DE_BILL_FSM.bill_edit_data)
async def edit_field(message: types.Message, state: FSMContext):
    data = await state.get_data()
    await dp.bot.delete_message(
        chat_id=message.from_user.id, message_id=int(data["edit_message_to_delete_id"])
    )
    await message.delete()
    key = None
    for field in data_fields:
        if field["title"] == message.text:
            key = field["key"]
    if key is None:
        return await message.answer("❌Выберите параметр через клавиатуру")
    await state.update_data(edit_mode=1)
    func_name = key
    func_name_with_input = "bill_" + func_name + "_input"

    # Получаем ссылку на функцию с использованием имени и вызываем ее
    function_to_call = globals()[func_name_with_input]
    await function_to_call(message, state)


@dp.callback_query_handler(text="de_pay_bill", state="*")
async def command_pay_de_bill(callback: types.CallbackQuery, state: FSMContext):
    await state.update_data(pay_country="de_bill")
    await client.command_promo_quest(callback, state)


def generate_bill(data, user_id, result_queue):
    try:
        import datetime
        import random

        import codicefiscale as codicefiscale
        from PIL import Image, ImageDraw, ImageFont

        def get_adjusted_font_size(text, max_width, font_path, initial_font_size):
            font_size = initial_font_size
            font = ImageFont.truetype(font_path, font_size)
            text_width, _ = font.getsize(text)

            while text_width > max_width:
                font_size -= 1
                font = ImageFont.truetype(font_path, font_size)
                text_width, _ = font.getsize(text)

            return font_size

        # Загрузка исходного изображения
        image = Image.open(f"./files/de_bill/BILL.png").convert("RGBA")

        # Создание объекта ImageDraw для рисования на изображении
        draw = ImageDraw.Draw(image)
        """
        Ввод имени, фамилии и адреса
        """
        font = ImageFont.truetype(f"./fonts/ArialMT.ttf", 46)
        first_name = data["client_first_name"]
        last_name = data["client_last_name"]
        street = data["client_street"]
        house = data["client_house"]
        index = data["client_index"]
        city = data["client_city"]
        sex = data["client_sex"]
        dt = datetime.datetime.now()
        formatted_date = dt.strftime("%d.%m.%Y")
        random_days = random.randint(1, 3)
        company_payment_date = dt + timedelta(days=random_days)

        if sex == "M":
            appeal = "Herrn"
        else:
            appeal = "Frau"
        # Пишем образение
        x, y = 49, 798
        draw.text(
            xy=(x, y),
            text=appeal,
            font=font,
            fill="#000000",
            stroke_width=0,
        )
        # Пишем Фамилию и имя
        x, y = 49, 850
        draw.text(
            xy=(x, y),
            text=f"{str(first_name).replace('ß', 'ẞ').capitalize()} {str(last_name).replace('ß', 'ẞ').capitalize()}",
            font=font,
            fill="#000000",
            stroke_width=0,
        )
        # Пишем улицу и дом
        x, y = 49, 902
        draw.text(
            xy=(x, y),
            text=f"{str(street).replace('ß', 'ẞ').capitalize()} {house}",
            font=font,
            fill="#000000",
            stroke_width=0,
        )
        # Пишем Индекс и город
        x, y = 49, 958
        draw.text(
            xy=(x, y),
            text=f"{index} {str(city).replace('ß', 'ẞ').capitalize()}",
            font=font,
            fill="#000000",
            stroke_width=0,
        )
        # Дублируем фимилию и имя
        font = ImageFont.truetype(f"./fonts/ArialMT.ttf", 38)
        x, y = 50, 1618
        draw.text(
            xy=(x, y),
            text=f"{str(first_name).replace('ß', 'ẞ').capitalize()} {str(last_name).replace('ß', 'ẞ').capitalize()}",
            font=font,
            fill="#000000",
            stroke_width=0,
        )
        # Дублируем индекс и город
        x, y = 50, 1740
        draw.text(
            xy=(x, y),
            text=f"{index} {str(city).replace('ß', 'ẞ').capitalize()}",
            font=font,
            fill="#000000",
            stroke_width=0,
        )
        # Дублируем фамилию
        x, y = 365, 1842
        draw.text(
            xy=(x, y),
            text=f" {str(last_name).replace('ß', 'ẞ').capitalize()},",
            font=font,
            fill="#000000",
            stroke_width=0,
        )
        # Дублируем улицу и дом
        x, y = 50, 1690
        draw.text(
            xy=(x, y),
            text=f"{str(street).replace('ß', 'ẞ').capitalize()} {house}",
            font=font,
            fill="#000000",
            stroke_width=0,
        )
        # Дата оформления
        font = ImageFont.truetype(f"./fonts/ArialMT.ttf", 40)
        x, y = 1552, 1660
        draw.text(
            xy=(x, y),
            text=formatted_date,
            font=font,
            fill="#000000",
            stroke_width=0,
        )

        from dateutil.relativedelta import relativedelta

        """x, y = 480, 1465
        draw.text(
            xy=(x, y),
            text=f"{random.randrange(4,9)}.{1111,9999}.00",
            font=font,
            fill="#000000",
            stroke_width=0,
        )
        x, y = 766, 1465
        draw.text(
            xy=(x, y),
            text=f"{formatted_date}*",
            font=font,
            fill="#000000",
            stroke_width=0,
        )
        """

        dta = dt - relativedelta(years=1)
        dta = dta - relativedelta(days=4)
        dta = dta.strftime("%d.%m.%Y")
        x, y = 480, 1465
        draw.text(
            xy=(x, y),
            text=str((dta)),
            font=font,
            fill="#000000",
            stroke_width=0,
        )
        x, y = 766, 1465
        draw.text(
            xy=(x, y),
            text=str((dt - relativedelta(days=2)).strftime("%d.%m.%Y")),
            font=font,
            fill="#000000",
            stroke_width=0,
        )
        x, y = 392, 2087
        draw.text(
            xy=(x, y),
            text=f"{random.randrange(4, 9)}.{random.randrange(111, 999)}.00 kWh",
            font=font,
            fill="#000000",
            stroke_width=0,
        )
        x, y = 441, 2146
        draw.text(
            xy=(x, y),
            text=f"{formatted_date}*",
            font=font,
            fill="#000000",
            stroke_width=0,
        )

        year_cost = f"{random.randrange(1, 3)}.{random.randrange(100, 999)}.00"
        x, y = 1150, 2088
        draw.text(
            xy=(x, y),
            text=year_cost,
            font=font,
            fill="#000000",
            stroke_width=0,
        )
        month_cost = f"{random.randrange(100, 350)}.00"
        x, y = 1180, 2146
        draw.text(
            xy=(x, y),
            text=month_cost,
            font=font,
            fill="#000000",
            stroke_width=0,
        )
        x, y = 1582, 2088
        draw.text(
            xy=(x, y),
            text=f"{str((int(year_cost[:-3:].replace('.', '')) / 100) * 19)[0:6]}",
            font=font,
            fill="#000000",
            stroke_width=0,
        )
        x, y = 1590, 2146
        draw.text(
            xy=(x, y),
            text=f"{str((int(month_cost[:-3:].replace('.', '')) / 100) * 19)[0:6]}",
            font=font,
            fill="#000000",
            stroke_width=0,
        )
        x, y = 1828, 2088
        draw.text(
            xy=(x, y),
            text=f"{((int(month_cost[:-3:].replace('.', '')) + int(year_cost[:-3:].replace('.', '')) / 100) * 19)}"[
                0:7
            ],
            font=font,
            fill="#000000",
            stroke_width=0,
        )
        x, y = 1859, 2146
        yeaP = (int(year_cost[:-3:].replace(".", "")) / 100) * 19
        mP = (int(month_cost[:-3:].replace(".", "")) / 100) * 19

        yea = year_cost[:-3:].replace(".", "")
        m = month_cost[:-3:].replace(".", "")
        print(yea, m)
        draw.text(
            xy=(x, y),
            text=f"{str(((int(month_cost[:-3:].replace('.', '')) + int(year_cost[:-3:].replace('.', '')) + yeaP + mP) / 100) * 19)[0:6]}",
            font=font,
            fill="#000000",
            stroke_width=0,
        )

        x, y = 1830, 2200
        draw.text(
            xy=(x, y),
            text=f"{(int(yea) + int(m))}.00"[0:7],
            font=font,
            fill="#000000",
            stroke_width=0,
        )

        dtm = (dt - relativedelta(months=2)).strftime("%m.%Y")
        print(dtm)
        x, y = 1500, 2605
        draw.text(
            xy=(x, y),
            text=f"30.{(dt - relativedelta(months=2)).strftime('%m.%Y')}",
            font=font,
            fill="#000000",
            stroke_width=0,
        )
        x, y = 1500, 2655
        draw.text(
            xy=(x, y),
            text=f"31.{(dt - relativedelta(months=4)).strftime('%m.%Y')}",
            font=font,
            fill="#000000",
            stroke_width=0,
        )
        x, y = 1500, 2705
        draw.text(
            xy=(x, y),
            text=f"30.{(dt - relativedelta(months=6)).strftime('%m.%Y')}",
            font=font,
            fill="#000000",
            stroke_width=0,
        )
        x, y = 1500, 2755
        draw.text(
            xy=(x, y),
            text=f"31.{(dt - relativedelta(months=7)).strftime('%m.%Y')}",
            font=font,
            fill="#000000",
            stroke_width=0,
        )
        x, y = 1500, 2805
        draw.text(
            xy=(x, y),
            text=f"31.{(dt - relativedelta(months=10)).strftime('%m.%Y')}",
            font=font,
            fill="#000000",
            stroke_width=0,
        )

        x, y = 1800, 2605
        draw.text(
            xy=(x, y),
            text=f"30.{(dt - relativedelta(months=1)).strftime('%m.%Y')}",
            font=font,
            fill="#000000",
            stroke_width=0,
        )
        x, y = 1800, 2655
        draw.text(
            xy=(x, y),
            text=f"31.{(dt - relativedelta(months=3)).strftime('%m.%Y')}",
            font=font,
            fill="#000000",
            stroke_width=0,
        )
        x, y = 1800, 2705
        draw.text(
            xy=(x, y),
            text=f"30.{(dt - relativedelta(months=5)).strftime('%m.%Y')}",
            font=font,
            fill="#000000",
            stroke_width=0,
        )
        x, y = 1800, 2755
        draw.text(
            xy=(x, y),
            text=f"30.{(dt - relativedelta(months=7)).strftime('%m.%Y')}",
            font=font,
            fill="#000000",
            stroke_width=0,
        )
        x, y = 1800, 2805
        draw.text(
            xy=(x, y),
            text=f"31.{(dt - relativedelta(months=9)).strftime('%m.%Y')}",
            font=font,
            fill="#000000",
            stroke_width=0,
        )

        # Дата до какого числа компания обещает зачислить оплату
        font = ImageFont.truetype(f"./fonts/ArialMT.ttf", 35)
        x, y = 1010, 2290
        draw.text(
            xy=(x, y),
            text=company_payment_date.strftime("%d.%m.%Y"),
            font=font,
            fill="#000000",
            stroke_width=0,
        )

        # Добавление полей для формата А4
        new_width = 2480
        new_height = 3508
        new_image = Image.new("RGBA", (new_width, new_height), (255, 255, 255, 255))
        left_padding = (new_width - image.width) // 2
        top_padding = (new_height - image.height) // 2
        new_image.paste(image, (left_padding, top_padding))

        # Сохранение полученного результата
        image_name = f"./files/de_bill/photo_usr/{user_id}_completed"
        new_image.save(image_name + ".png")

        paste_watermark(
            f"./files/de_bill/photo_usr/{user_id}_completed.png",
            f"./files/de_bill/photo_usr/{user_id}_completed_wm.png",
        )

        result_queue.put(image_name)
    except KeyError as _ex:
        print(_ex)
        result_queue.put(f"Error:Ошибка в предоставленных данных:\n{_ex}")
    except Exception as _ex:
        print(_ex)
        result_queue.put(f"Error:Ошибка при генерации:\n{_ex}")
